package com.mikhailenko.transportMVC.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.mikhailenko.transportMVC.exeption.TermNotFoundExeption;
import com.mikhailenko.transportMVC.model.Term;
import com.mikhailenko.transportMVC.repository.TermRepository;
import com.mikhailenko.transportMVC.service.TermService;

@Service
public class TermServiceImpl implements TermService {

	@Autowired
	private TermRepository termRepository;
	
	@Override
	@Transactional
	public Term create(Term term) {
		Term createdTerm = term;
		return termRepository.saveAndFlush(createdTerm);
	}

	@Override
	@Transactional(rollbackFor=TermNotFoundExeption.class)
	public Term delete(int id) throws TermNotFoundExeption {
		Term deletedTerm = termRepository.findOne(id);
		
		if (deletedTerm == null){
			throw new TermNotFoundExeption();
		}
		
		termRepository.delete(id);
		return deletedTerm;
	}

	@Override
	@Transactional
	public List<Term> findAll() {
		return termRepository.findAll();
	}

	@Override
	@Transactional(rollbackFor=TermNotFoundExeption.class)
	public Term update(Term term) throws TermNotFoundExeption {
		Term updatedTerm = termRepository.findOne(term.getId());
		
		if (updatedTerm == null) {
			throw new TermNotFoundExeption();
		}
		
//		updatedTerm.setCriteria(term.getCriteria());
		updatedTerm.setFunction(term.getFunction());
		updatedTerm.setMaxValue(term.getMaxValue());
		updatedTerm.setMiddleValue(term.getMiddleValue());
		updatedTerm.setMinValue(term.getMinValue());
		updatedTerm.setName(term.getName());
		return updatedTerm;
	}

	@Override
	@Transactional
	public Term findById(int id) {
		return termRepository.findOne(id);
	}

	@Override
	public Term findbyName(String name) {
		return termRepository.findByName(name);
	}

}
